import { createRouter, createWebHistory } from 'vue-router';
import type { Router } from 'vue-router';
import { values } from 'lodash-es';

import { constantRoutes } from './constant-routes';

type RouterGuardSetter = (router: Router) => void;

const guardModules: Recordable<RouterGuardSetter> = import.meta.glob('./guards/**/*.ts', {
  eager: true,
  import: 'default',
  exhaustive: false,
});

const router = createRouter({
  history: createWebHistory(),
  strict: false,
  routes: constantRoutes,
  // 刷新时，滚动条位置还原
  scrollBehavior(_to, _from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

for (const guard of values(guardModules)) {
  guard.call(undefined, router);
}

export default router;
